<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<script type="text/javascript" src="./lib/cuon-matrix.js"></script>
<script type="text/javascript" src="./lib/cuon-utils.js"></script>
<script type="text/javascript" src="./lib/webgl-debug.js"></script>
<script type="text/javascript" src="./lib/webgl-utils.js"></script>
<script type="text/javascript">

var VSHADER_SOURCE =
'attribute vec4 a_Position;'+
'void main(){'+
'gl_Position = a_Position;'+
'gl_PointSize = 20.0;}';

var FSHADER_SOURCE =
'precision mediump float;'+
'uniform vec4 u_FragColor;'+
'void main(){'+
'float d = distance(gl_PointCoord, vec2(0.5, 0.5));'+
'if(d < 0.5) {' +  // Radius is 0.5
'gl_FragColor = u_FragColor;' +
'  } else { discard; }' +
'}';
var paint = false;
var g_pointsx = [];
var g_pointsy = [];

function start () {
	var canvas = document.getElementById('webgl');
	//canvas.width = document.documentElement.clientWidth;
	//canvas.height = document.documentElement.clientHeight;
	var gl  = getWebGLContext(canvas);
	if (!gl){
		alert('gl 初始化失败');
		return;
	}

	if(!initShaders(gl,VSHADER_SOURCE,FSHADER_SOURCE)){
		alert('gl 着色器失败');
		return;
	}

	var a_Position =gl.getAttribLocation(gl.program,'a_Position');
	if (a_Position < 0) {
		alert('a_Position 失败');
		return;
	}

	var u_FragColor = gl.getUniformLocation(gl.program,'u_FragColor');
	if (!u_FragColor){
		alert('u_FragColor 失败');
		return
	}

	canvas.onmouseup = function(ev){ click(ev, gl, canvas, a_Position,u_FragColor); };

	// gl.vertexAttrib4f(a_Position,0.0,0.0,0.0,1.0);
	gl.clearColor(0.0,0.0,0.0,1.0);
	gl.clear(gl.COLOR_BUFFER_BIT);
	// gl.drawArrays(gl.POINTS,0,1);

}


function click(ev, gl, canvas, a_Position,u_FragColor) {
  var xy  = getClickPosition(ev)
  g_pointsx.push(xy.x);
  g_pointsy.push(xy.y);

  gl.clear(gl.COLOR_BUFFER_BIT);
  for(var i=0;i<g_pointsx.length;++i){
  	gl.vertexAttrib2f(a_Position,g_pointsx[i],g_pointsy[i]);
  	gl.uniform4f(u_FragColor, 0.0, 1.0, 0.0, 1.0);
  	gl.drawArrays(gl.POINTS,0,1);
	}
  console.log(xy)
}

function getClickPosition(ev){
  var x = ev.clientX;
  var y = ev.clientY;
  var rect = ev.target.getBoundingClientRect();

  x = x - rect.left;
  x = (x - rect.width/2) / (rect.width/2);

  y = y - rect.top;
  y = (rect.height/2 - y) /(rect.height/2);
  return {x,y}
}

</script>

<body onload="start()">
	<canvas id = "webgl" width="500" height="500"></canvas>
</body>
</html>